package com.gzx.spring.apis.utils;

import com.alibaba.fastjson2.JSONObject;
import com.gzx.risk.core.utils.AESUtils;
import com.gzx.risk.core.utils.CryptoUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class BairongUtil {

    private String strategy_id;// 贷前策略编号
    private String apiName; // 贷前策略api（/strategy_api/v3/hx_query） / 信息验证api（/infoverify/v3/info_verify）
    private String apiCode; // 测试：3035275  正式：3035202
    private String appKey; // 正式：b4c8d24b26de4314c4992534772d34f6d277a00f87bbaf8879e009707fce064d
    private String domain; // 域名

    private String exec(Map<String, String> params) throws Exception {

        JSONObject jso = new JSONObject();
        //策略贷前接口
        jso.put("reqData", params);
        String fullUrl = getFullUrl(domain, apiName);
        HttpPost httpPost = new HttpPost(fullUrl);
        Map<String, Object> reqParams = dealParams(params.toString(), apiCode, appKey);
        setFormParams(httpPost,reqParams);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000)
                .setConnectionRequestTimeout(3000)
                .setSocketTimeout(5000).setCookieSpec("best-match").build();
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
        CloseableHttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        EntityUtils.consume(entity);
        return result;
    }

    /**
     * 贷前策略 - 借贷意向验证3.0-当日版
     *
     * @param name   姓名
     * @param idCard 身份证
     * @param phone  手机哈
     * @return
     * @throws Exception
     */
    public String applyEvaluate_d(String name, String idCard, String phone) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("strategy_id", strategy_id);
        params.put("id",CryptoUtils.MD5(idCard));
        params.put("cell", CryptoUtils.MD5(phone));
        params.put("name", name);
        return exec(params);
    }

    private String getFullUrl(String domain, String reqPath) {
        String fullUrl = domain + reqPath;
        if (!domain.startsWith("https://") && !domain.startsWith("http://")) {
            fullUrl = "https://" + fullUrl;
        }
        return fullUrl;
    }

    /**
     * 处理 application/x-www-form-urlencoded 格式（符合接入约定）
     */
    private void setFormParams(HttpPost httpPost, Map<String, Object> params) {
        try {
            List<NameValuePair> nvps = new ArrayList<>();
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue() != null ? entry.getValue().toString() : "";
                nvps.add(new BasicNameValuePair(key, value));
            }
            // 自动处理 URL 编码和 Content-Type
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, StandardCharsets.UTF_8.toString()));
        } catch (Exception e) {
            log.error("表单参数处理失败", e);
            throw new RuntimeException("表单参数错误", e);
        }
    }

    private Map<String, Object> dealParams(String reqData, String apiCode, String appKey) throws Exception {

        String checkCode = CryptoUtils.MD5(reqData + apiCode + appKey);
        String encryptJsonData = AESUtils.encryptBr(URLEncoder.encode(reqData, StandardCharsets.UTF_8.name()), appKey);

        Map<String, Object> paramMap = new HashMap();
        String appKeyEncrypt = CryptoUtils.MD5(appKey);

        paramMap.put("jsonData", encryptJsonData);
        paramMap.put("appKey", appKeyEncrypt);
        paramMap.put("apiCode", apiCode);
        paramMap.put("checkCode", checkCode);
        return paramMap;
    }
}
